package com.ruoyix.common.filter;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.ruoyix.common.utils.StringUtils;
import org.springframework.http.MediaType;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Repeatable 过滤器
 *
 * @author ruoyi
 */
public class RepeatableFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        // 获取原始的HttpServletRequest对象
        HttpServletRequest httpRequest = request instanceof HttpServletRequest ? (HttpServletRequest) request : null;

        // 打印请求的IP地址
        if (httpRequest != null) {
            String clientIp = JakartaServletUtil.getClientIP(httpRequest);
            System.out.println("Client IP: " + clientIp); // 或者使用日志框架进行记录
        }

        ServletRequest requestWrapper = null;
        if (httpRequest != null
            && StringUtils.startsWithIgnoreCase(httpRequest.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            requestWrapper = new RepeatedlyRequestWrapper(httpRequest, response);
        }

        // 使用包装过的请求或者原始请求继续过滤链
        chain.doFilter(null == requestWrapper ? request : requestWrapper, response);
    }

    @Override
    public void destroy() {

    }
}
